package com.xmb.wechat.view.wechat.chat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dmcbig.mediapicker.PickerConfig;
import com.dmcbig.mediapicker.entity.Media;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.PYQCommentsBean;
import com.xmb.wechat.bean.PYQPicBean;
import com.xmb.wechat.bean.PYQTrendsBean;
import com.xmb.wechat.bean.PYQTrendsBean_;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.definterface.PYQPicDelegateListener;
import com.xmb.wechat.delegate.PYQAddPicDelegate;
import com.xmb.wechat.dialog.BigPicDialog;
import com.xmb.wechat.util.PicChooseUtils;
import com.xmb.wechat.widget.TitleLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author lijiangop
 * @CreateTime 2020/5/9 15:31
 */
public class WechatPYQAddActivity extends BaseActivity {

    private static final int REQUEST_CODE_ADD_LIKES    = 103;
    private static final int REQUEST_CODE_ADD_COMMENTS = 104;
    private static final int REQUEST_CODE_IMAGE        = 105;

    @BindView(R2.id.title_layout)
    TitleLayout  mTitleLayout;
    @BindView(R2.id.tv_owner)
    TextView     mTvOwner;
    @BindView(R2.id.iv_owner)
    ImageView    mIvOwner;
    @BindView(R2.id.et_time)
    EditText     mEtTime;
    @BindView(R2.id.switch_show_location)
    Switch       mSwitchShowLocation;
    @BindView(R2.id.et_location_city)
    EditText     mEtLocationCity;
    @BindView(R2.id.ll_location_city)
    LinearLayout mLlLocationCity;
    @BindView(R2.id.et_location_detail)
    EditText     mEtLocationDetail;
    @BindView(R2.id.ll_location_detail)
    LinearLayout mLlLocationDetail;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.et_content)
    EditText     mEtContent;
    @BindView(R2.id.tv_likes)
    TextView     mTvLikes;
    @BindView(R2.id.tv_comments)
    TextView     mTvComments;

    private boolean           isShowLocation;
    private PYQAddPicDelegate mDelegate;
    private BigPicDialog      mBigPicDialog;
    private PYQTrendsBean     mPyqEntity;

    public WechatPYQAddActivity() {
        super(R.layout.activity_wechat_pyq_add);
    }

    public static void startForResult(Activity ctx, long entityId, int requestCode) {
        Intent intent = new Intent(ctx, WechatPYQAddActivity.class);
        intent.putExtra("id", entityId);
        ctx.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void initView() {
        //init view
        mTitleLayout.setRightClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doConfirm();
            }
        });
        mSwitchShowLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isShowLocation = isChecked;
                mPyqEntity.setShowLocation(isShowLocation);
                mLlLocationCity.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                mLlLocationDetail.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });
        mDelegate = new PYQAddPicDelegate(WechatPYQAddActivity.this, mRecyclerView, new PYQPicDelegateListener() {
            @Override
            public void onAdd() {
                PicChooseUtils.choosePyqPics(WechatPYQAddActivity.this, REQUEST_CODE_IMAGE, mDelegate.getData());
            }

            @Override
            public void onOpen(String path) {
                if (mBigPicDialog == null)
                    mBigPicDialog = new BigPicDialog(WechatPYQAddActivity.this);
                mBigPicDialog.showImageView(path);
                mBigPicDialog.show();
            }
        });
        //getData
        long id = getIntent().getLongExtra("id", -1);
        if (id < -1)
            mPyqEntity = null;
        else
            mPyqEntity = WechatStartApplication.getBoxStore().boxFor(PYQTrendsBean.class).query().equal(PYQTrendsBean_.id, id).build().findUnique();
        //showView
        if (mPyqEntity == null) {//新增
            mPyqEntity = new PYQTrendsBean();
            mDelegate.additem(new PYQPicBean());//添加按钮数据
        } else {//编辑
            //发送人
            WechatContactBean sender = WechatContactBean.getWechatContactBean(this, mPyqEntity.getSenderId(), false);
            if (sender != null) {
                mTvOwner.setText(sender.getName());
                WechatContactBean.setupAvatarIntoImageView(sender, mIvOwner);
            }
            //时间
            mEtTime.setText(TextUtils.isEmpty(mPyqEntity.getTime()) ? "" : mPyqEntity.getTime());
            //位置信息
            if (mPyqEntity.isShowLocation()) {
                mSwitchShowLocation.setChecked(true);
                mEtLocationCity.setText(TextUtils.isEmpty(mPyqEntity.getLocationCity()) ? "" : mPyqEntity.getLocationCity());
                mEtLocationDetail.setText(TextUtils.isEmpty(mPyqEntity.getLocationDetail()) ? "" : mPyqEntity.getLocationDetail());
            }
            //动态内容
            mEtContent.setText(TextUtils.isEmpty(mPyqEntity.getContent()) ? "" : mPyqEntity.getContent());
            //动态图片
            mDelegate.addData(mPyqEntity.getPics());
            //点赞
            showLikes(mPyqEntity.getLikes());
            //评论
            mTvComments.setText(mPyqEntity.getComments().size() + "条");
        }
    }

    @OnClick({R2.id.re_sender, R2.id.ll_likes, R2.id.ll_comments, R2.id.btn_preview})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.re_sender) {
            showRoleChooseSender(WechatPYQAddActivity.this,true, false, this::showSenderResult);
        } else if (id == R.id.ll_likes) {
            WechatPYQAddLikesActivity.start4Result(WechatPYQAddActivity.this, mPyqEntity.getLikes(), REQUEST_CODE_ADD_LIKES);
        } else if (id == R.id.ll_comments) {
            WechatPYQCommentsActivity.start4Result(WechatPYQAddActivity.this, mPyqEntity.getComments(), REQUEST_CODE_ADD_COMMENTS);
        } else if (id == R.id.btn_preview) {
            doConfirm();
        }
    }

    private void doConfirm() {
        //发送人
        if (mPyqEntity.getSenderId() == -2) {
            ToastUtils.showShort("请选择发送人");
            return;
        }
        //时间信息
        String time = mEtTime.getText().toString().trim();
        if (TextUtils.isEmpty(time)) {
            ToastUtils.showShort("请填写发布时间");
            return;
        }
        mPyqEntity.setTime(time);
        //位置信息
        String city = mEtLocationCity.getText().toString().trim();
        String locationDetail = mEtLocationDetail.getText().toString().trim();
        if (isShowLocation) {
            if (TextUtils.isEmpty(city)) {
                ToastUtils.showShort("请填写具体城市");
                return;
            }
            if (TextUtils.isEmpty(locationDetail)) {
                ToastUtils.showShort("请填写具体位置");
                return;
            }
            mPyqEntity.setLocationCity(city);
            mPyqEntity.setLocationDetail(locationDetail);
        }
        //动态内容
        //文字
        String trendsContent = mEtContent.getText().toString().trim();
        mPyqEntity.setContent(trendsContent);
        //图片
        List<PYQPicBean> data = mDelegate.getData();
        mPyqEntity.getPics().clear();
        if (data.size() != 0)
            mPyqEntity.getPics().addAll(data);
        if (TextUtils.isEmpty(trendsContent) && data.size() == 1) {
            ToastUtils.showShort("动态内容的文字消息和图片消息不能同时为空");
            return;
        }
        KeyboardUtils.hideSoftInput(WechatPYQAddActivity.this);
        WechatStartApplication.getBoxStore().boxFor(PYQTrendsBean.class).put(mPyqEntity);
        Intent intent = new Intent().putExtra("data", mPyqEntity);
        setResult(RESULT_OK, intent);
        finish();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_OTHER_SEND || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_SEND) {//选择发送人
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            showSenderResult(result);
        } else if (requestCode == REQUEST_CODE_ADD_LIKES) {//点赞
            if (data == null)
                return;
            showLikes(data.getStringExtra("result"));
        } else if (requestCode == REQUEST_CODE_ADD_COMMENTS) {//评论
            if (data == null)
                return;
            Bundle bundle = data.getBundleExtra("bundle");
            if (bundle == null)
                return;
            ArrayList<PYQCommentsBean> result = (ArrayList<PYQCommentsBean>) bundle.getSerializable("data");
            showCommentsResult(result);
        } else if (requestCode == REQUEST_CODE_IMAGE && resultCode == PickerConfig.RESULT_CODE) {//选择多张图片
            try {
                ArrayList<Media> listExtra = data.getParcelableArrayListExtra(PickerConfig.EXTRA_RESULT);
                if (null == listExtra || listExtra.size() == 0)
                    return;
                //去掉加号(能回调这个方法，就表示肯定还有加号，图片选择处已做判断)
                mDelegate.removeItem(mDelegate.getData().size() - 1);
                //添加图片
                for (Media media : listExtra) {
                    mDelegate.additem(new PYQPicBean(media.path));
                }
                if (mDelegate.getData().size() < 9) //添加加号
                    mDelegate.additem(new PYQPicBean());
            } catch (Exception e) {
                ToastUtils.showLong("图片选择出错");
            }
        }
    }

    private void showSenderResult(WechatContactBean contactBean) {
        if (contactBean == null)
            return;
        mTvOwner.setText(contactBean.getName());
        WechatContactBean.setupAvatarIntoImageView(contactBean, mIvOwner);
        mPyqEntity.setSenderId(contactBean.getId());
    }

    private void showLikes(String result) {
        int number;
        if (TextUtils.isEmpty(result)) {
            number = 0;
        } else {
            if (result.contains(",")) {
                String[] split = result.split(",");
                number = split.length;
            } else {
                number = 1;
            }
        }
        mTvLikes.setText(number + "人");
        mPyqEntity.setLikes(result);
    }

    private void showCommentsResult(ArrayList<PYQCommentsBean> result) {
        if (result == null)
            return;
        mTvComments.setText(result.size() + "条");
        mPyqEntity.getComments().clear();
        mPyqEntity.getComments().addAll(result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBigPicDialog != null) {
            mBigPicDialog.dismiss();
            mBigPicDialog = null;
        }
    }
}
